package com.ethink.order.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author default
 * @version 1.0.0
 * @ClassName SaleChannelRequestManager.java
 * @Description
 * @createTime 2022年11月08日 13:56:00
 */
@Slf4j
public class SaleChannelRequestManager {


    public static void fill(Object source, int sourceIndex, int targetIndex1, int targetIndex2) {
        List<Map<String, Object>> fieldInfo = getFieldInfo(source);
        if (CollUtil.isEmpty(fieldInfo)) {
            return;
        }
        String[] arr = (String[]) fieldInfo.get(sourceIndex).get("value");
        if (ArrayUtil.isNotEmpty(arr)) {
            try {
                if (arr.length > 1) {
                    Field filed = source.getClass().getDeclaredField(fieldInfo.get(targetIndex2).get("name").toString());
                    filed.setAccessible(true);
                    filed.set(source, arr[1]);
                }
                Field filed = source.getClass().getDeclaredField(fieldInfo.get(targetIndex1).get("name").toString());
                filed.setAccessible(true);
                filed.set(source, arr[0]);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                e.printStackTrace();
            }
        }

    }

    public static List<Map<String, Object>> getFieldInfo(Object o) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (ObjectUtil.isEmpty(o)) {
            return null;
        }
        List<Field> fields = new ArrayList<>(Arrays.asList(o.getClass().getDeclaredFields()));
        //未考虑父类
        for (Field field : fields) {
            Map<String, Object> infoMap = new HashMap<>();
            infoMap.put("type", field.getType().toString());
            infoMap.put("name", field.getName());
            infoMap.put("value", getFieldValueByName(field.getName(), o));
            list.add(infoMap);
        }
        return list;
    }

    public static Object getFieldValueByName(String fileName, Object o) {
        try {
            String firstLetter = fileName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fileName.substring(1);
            Method method = o.getClass().getMethod(getter);
            return method.invoke(o);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
